package net.maergaiyun.controller;


import net.maergaiyun.service.DomainService;
import net.maergaiyun.util.JsonData;
import net.maergaiyun.vo.DomainVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author maergaiyun
 * @since 2024-08-28
 */
@RestController
@RequestMapping("/api/domain/v1")
public class DomainController {
    @Autowired
    private DomainService domainService;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @PostMapping("/list")
    public JsonData listAll() {
        List<DomainVO> domainVOList = domainService.listAll();
        return JsonData.buildSuccess(domainVOList);
    }

    @GetMapping("/test")
    public JsonData test(@RequestParam(name = "code") String code, @RequestParam(name = "accountNo") Long accountNo) {
        String script = "if redis.call('EXISTS',KEYS[1])==0 then redis.call('set',KEYS[1],ARGV[1]); redis.call('expire',KEYS[1],ARGV[2]); return 1;" + " elseif redis.call('get',KEYS[1]) == ARGV[1] then return 2;" + " else return 0; end;";
        Long result = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Arrays.asList(code), accountNo, 100);
        return JsonData.buildSuccess(result);
    }

}

